import { IArrayUtils } from '../interface/IArrayUtils';

/**
 * 数组操作hook
 * @implements {IArrayUtils}
 */
class ArrayUtils implements IArrayUtils {
  constructor() {}

  public duplicateRemoval_set(arr: any[]) {
    return Array.from(new Set(arr));
  }

  public groupBy(arr: any[], generateKey: string | Function): {} {
    if (typeof generateKey === 'string') {
      const propName: string = generateKey;
      generateKey = (item: any) => item[propName];
    }
    const result: any = {};

    for (const item of arr) {
      const key = generateKey(item);

      if (!result[key]) {
        result[key] = [];
      }
      result[key].push(item);
    }
    return result;
  }
}

/*
* 示例
* const arr: {}[] = [
  {name: '12', age: 12, sex: 'male', address: {city: '河南', province: '商丘'}},
  {name: '13', age: 16, sex: 'female', address: {city: '山东', province: '菏泽'}},
  {name: '14', age: 15, sex: 'male', address: {city: '山东', province: '菏泽'}},
  {name: '12', age: 12, sex: 'female', address: {city: '河南', province: '商丘'}},
  {name: '13', age: 16, sex: 'female', address: {city: '山东', province: '济南'}},
  {name: '14', age: 15, sex: 'female', address: {city: '山东', province: '济南'}},
  {name: '12', age: 12, sex: 'female', address: {city: '河南', province: '商丘'}},
]

groupBy(arr, 'name')
groupBy(arr, (item: any) => `${item.age}-${item.sex}`)
*
* */

const arrayUtils = new ArrayUtils();
export default arrayUtils;
